<template>

    <el-form ref="ruleFormRef" style="max-width: 600px;margin: 300px 600px; " :model="ruleForm" :rules="rules"
        label-width="auto" class="demo-ruleForm" :size="formSize" status-icon>
        <el-form-item label="用户名" prop="name">
            <el-input v-model="ruleForm.name" />
        </el-form-item>
        <el-form-item label="密码" prop="pwd">
            <el-input v-model="ruleForm.pwd" />
        </el-form-item>
        <el-checkbox v-model="ruleForm.jizhu" label="记住密码?" size="large" />
        <el-form-item>
            <el-button type="primary" @click="submitForm(ruleFormRef)">
                登录
            </el-button>
            <el-button @click="resetForm(ruleFormRef)">重置</el-button>
        </el-form-item>
    </el-form>

</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'
import { ElMessage, type ComponentSize, type FormInstance, type FormRules } from 'element-plus'
import Cookie from 'js-cookie';
import router from '@/router';

const formSize = ref<ComponentSize>('default')
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
    name: '',
    pwd: '',
    jizhu: false
})


const rules = reactive<FormRules>({
    name: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 12, message: '用户名长度为3-12位', trigger: 'blur' },
    ],
    pwd: [
        {
            required: true,
            message: '请输入密码',
            trigger: 'blur',
        },
    ]
})

const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {

            if (ruleForm.name == 'admin' && ruleForm.pwd == '123456') {
                ElMessage.success("登录成功");
            
                if (ruleForm.jizhu) {
                    Cookie.set('name', ruleForm.name, { expires: 7 });
                    Cookie.set('pwd', ruleForm.pwd, { expires: 7 });
                    Cookie.set('jizhu', ruleForm.jizhu?1:0, { expires: 7 });
                }
                router.push('/main');
            }

        } else {
            console.log('error submit!', fields)
        }
    })
}

const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}

const options = Array.from({ length: 10000 }).map((_, idx) => ({
    value: `${idx + 1}`,
    label: `${idx + 1}`,
}))


const jiZhuMima = () => {
    if(Cookie.get("jizhu")==1){
    ruleForm.name = Cookie.get('name') || ''
    ruleForm.pwd = Cookie.get('pwd') || ''
    ruleForm.jizhu = true
    }
    
}

onMounted(() => {
    jiZhuMima();
});
</script>